/*
 * @Author: your name
 * @Date: 2021-02-27 23:28:15
 * @LastEditTime: 2021-07-22 16:32:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue3-antd-koa\koa-api\src\controllers\article.js
 */
const { schema } = require("../pipe/article")
const { Sequelize, Op } = require("sequelize")

/**
 * @type {Custom.Controller<"archives">}
 */
module.exports = {
	async index(ctx, next) {
		// const { page, limit, type } = await schema.index.validateAsync(ctx.query)
		// const offset = limit * (page - 1)
		// const articles = await ctx.model.Article.findAll({
		// 	limit,
		// 	offset,
		// 	order: [["id", "DESC"]],
		// 	where: { type }
		// })
		// ctx.success(articles)
		// await next()
		const { page, limit, type } = await schema.index.validateAsync(ctx.query)
		const offset = limit * (page - 1)
		const articles = await ctx.model.Article.findAndCountAll({
			limit,
			offset,
			order: [['id', 'DESC']],
			where: { type }
		})
		ctx.success(articles)
		await next()
	},
	async show(ctx, next) {
		// const { id } = await schema.show.validateAsync(ctx.params)
		// const article = await ctx.model.Article.findByPk(id, {
		// 	includes: {
		// 		model: ctx.model.User,
		// 		attributes: {
		// 			exclude: ['password']
		// 		}
		// 	}
		// })
		// if (!article) {
		// 	return ctx.success('文章未找到，请确定文章id', 404)
		// }
		// ctx.success(article)
		// await next()
		const { id } = await schema.show.validateAsync(ctx.params)
		const article = await ctx.model.Article.findByPk(id, {
			includes: {
				model: ctx.model.User,
				attributes: {
					exclude: ['password']
				}
			}
		})
		if (!article) {
			return ctx.success('文章未找到，请确定文章id', 404)

		}
		ctx.success(article)
		await next();
	},
	/**
	 * @description 创建文章
	 * @param {*} ctx 
	 * @param {*} next 
	 */
	async create(ctx, next) {
		// const { id: user_id } = ctx.state.user // token 里面存的信息被放在ctx.state里面
		// const newInfo = await schema.create.validateAsync(ctx.request.body)
		// const article = await ctx.model.Article.create({
		// 	...newInfo,
		// 	UserId: user_id
		// })
		// ctx.success(article)
		// await next()
		const { id: user_id } = ctx.state.user // token 里面存的信息被放在ctx.state里面
		const newInfo = await schema.create.validateAsync(ctx.request.body);
		const article = await ctx.model.Article.create({
			...newInfo,
			UserId: user_id
		})
		ctx.success(article)
		await next()

	},
	async update(ctx, next) {
		const { id: user_id } = ctx.state.user // token 里面存的信息被放在ctx.state里面
		const { id, ...newInfo } = await schema.update.validateAsync({
			...ctx.params,
			...ctx.request.body
		})
		const article = await ctx.model.Article.findByPk(id)
		// 文章不存在的情况
		if (!article) {
			return ctx.fail("更新文章失败，文章未找到，请确认文章ID", 400)
		}
		const userIdIsEqual = article.UserId === user_id
		if (!userIdIsEqual) {
			return ctx.fail("该用户无权更新此文章")
		}
		await article.update(newInfo)
		ctx.success(article, 201)
		next()
	},
	// 文章删除
	async destroy(ctx, next) {
		const { id: user_id } = ctx.state.user // token 里面存的信息被放在ctx.state里面
		const { id } = await schema.destroy.validateAsync({
			...ctx.params
		})
		const article = await ctx.model.Article.findByPk(id)
		// 文章不存在的情况
		if (!article) {
			return ctx.fail("删除文章失败，文章未找到，请确认文章ID", 400)
		}
		const userIdIsEqual = article.UserId === user_id
		if (!userIdIsEqual) {
			return ctx.fail("该用户无权删除此文章")
		}
		await article.destroy()
		ctx.success(null, 204)
		next()
	},

	// 归档
	async archives(ctx, next) {
		const articles = await ctx.model.Article.findAll({
			order: [["id", "DESC"]],
			group: Sequelize.fn(
				"date_format",
				Sequelize.col("createdAt"),
				"%Y-%m"
			),
			attributes: [
				[
					Sequelize.fn(
						"date_format",
						Sequelize.col("createdAt"),
						"%Y-%m"
					),
					"month"
				] // 添加一个字段别名 为month
			],
			raw: true // 对象的方式返回
		});
		/**
		 * 上面返回的格式
			{
			data:[{
					month:xxx	
				}]
			}
		 */

		for (const item of articles) {
			item.data = await ctx.model.Article.findAll({
				order: [["id", "DESC"]],
				where: {
					createdAt: {
						[Op.like]: `${item.month}%`
					}
				},
				attributes: [
					"id",
					"title",
					[
						Sequelize.fn(
							"date_format",
							Sequelize.col("createdAt"),
							"%Y-%m-%d"
						),
						"createdAt"
					]
				]
			})
		}

		ctx.success(articles)
		await next();
	}
}